use crate::cli::types::*;
use crate::config::Config;
use crate::generator::{GenerationContext, Generator};
use anyhow::{Context, Result};
use colored::*;
use inquire::{Confirm, MultiSelect, Select, Text};
use std::path::PathBuf;

/// 创建新扩展项目的命令
pub struct NewCommand {
    name: String,
    description: Option<String>,
    output: Option<PathBuf>,
    extension_type: ExtensionType,
    layers: Option<Vec<LayerType>>,
    author: Option<String>,
    force: bool,
    interactive: bool,
}

impl NewCommand {
    pub fn new(
        name: String,
        description: Option<String>,
        output: Option<PathBuf>,
        extension_type: ExtensionType,
        layers: Option<Vec<LayerType>>,
        author: Option<String>,
        force: bool,
        interactive: bool,
    ) -> Self {
        Self { name, description, output, extension_type, layers, author, force, interactive }
    }

    pub async fn execute(mut self) -> Result<()> {
        if self.interactive {
            self = self.run_interactive_mode().await?;
        }

        // 验证名称
        self.validate_name()?;

        // 创建生成上下文
        let context = GenerationContext::new(
            self.name.clone(),
            self.description.clone(),
            self.extension_type.clone(),
            self.layers.clone(),
            self.author.clone(),
            self.output.clone(),
        );

        // 检查输出目录
        if context.output_dir.exists() && !self.force {
            if !Confirm::new(&format!("目录 {} 已存在，是否继续？这将覆盖现有文件。", context.output_dir.display().to_string().cyan()))
                .with_default(false)
                .prompt()?
            {
                println!("{}", "操作已取消".yellow());
                return Ok(());
            }
        }

        // 显示生成信息
        self.print_generation_info(&context);

        // 生成项目
        let generator = Generator::new();
        generator.generate(&context).await?;

        // 显示成功信息
        self.print_success_info(&context);

        Ok(())
    }

    async fn run_interactive_mode(mut self) -> Result<Self> {
        println!("{}", "🎯 交互式扩展项目生成".bold().cyan());
        println!();

        // 扩展名称
        if self.name.is_empty() {
            self.name = Text::new("扩展名称 (例如: djgc, fbfx-csxm):")
                .with_validator(|input: &str| {
                    if input.trim().is_empty() {
                        Ok(inquire::validator::Validation::Invalid("扩展名称不能为空".into()))
                    } else if !input.chars().all(|c| c.is_alphanumeric() || c == '-') {
                        Ok(inquire::validator::Validation::Invalid("扩展名称只能包含字母、数字和连字符".into()))
                    } else {
                        Ok(inquire::validator::Validation::Valid)
                    }
                })
                .prompt()?;
        }

        // 扩展描述
        if self.description.is_none() {
            let desc = Text::new("扩展描述:").with_default(&format!("{} extension for Price-RS", self.name)).prompt()?;
            self.description = Some(desc);
        }

        // 扩展类型
        let extension_types =
            vec![ExtensionType::Standard, ExtensionType::Api, ExtensionType::Core, ExtensionType::Lightweight, ExtensionType::Custom];

        self.extension_type = Select::new("选择扩展类型:", extension_types).prompt()?;

        // 自定义层选择（仅当选择 Custom 类型时）
        if matches!(self.extension_type, ExtensionType::Custom) {
            let all_layers = vec![LayerType::Nodes, LayerType::Plugins, LayerType::Commands, LayerType::Router];

            let selected = MultiSelect::new("选择要包含的层:", all_layers)
                .with_formatter(&|layers| layers.iter().map(|l| format!("{:?}", l)).collect::<Vec<_>>().join(", "))
                .prompt()?;

            self.layers = Some(selected);
        }

        // 作者信息
        if self.author.is_none() {
            let config = Config::load().unwrap_or_default();
            let default_author = config.default_author.unwrap_or_else(|| "Price-RS Team".to_string());

            let author = Text::new("作者:").with_default(&default_author).prompt()?;
            self.author = Some(author);
        }

        // 输出目录
        if self.output.is_none() {
            let default_output = format!("extension-{}", self.name);
            let output = Text::new("输出目录:").with_default(&default_output).prompt()?;
            self.output = Some(PathBuf::from(output));
        }

        println!();
        Ok(self)
    }

    fn validate_name(&self) -> Result<()> {
        if self.name.is_empty() {
            anyhow::bail!("扩展名称不能为空");
        }

        if !self.name.chars().all(|c| c.is_alphanumeric() || c == '-') {
            anyhow::bail!("扩展名称只能包含字母、数字和连字符");
        }

        if self.name.len() > 50 {
            anyhow::bail!("扩展名称不能超过50个字符");
        }

        Ok(())
    }

    fn print_generation_info(
        &self,
        context: &GenerationContext,
    ) {
        println!("{}", "📋 生成配置信息".bold());
        println!("  {} {}", "名称:".cyan(), context.name.bold());
        println!("  {} {}", "描述:".cyan(), context.description);
        println!("  {} {:?}", "类型:".cyan(), context.extension_type);
        println!("  {} {}", "输出:".cyan(), context.output_dir.display());
        println!("  {} {}", "作者:".cyan(), context.author);

        println!("\n{}", "🏗️  包含的层:".bold());
        for layer in &context.enabled_layers {
            println!("  {} {} - {}", "✓".green(), format!("{:?}", layer).bold(), layer.description().italic());
        }
        println!();
    }

    fn print_success_info(
        &self,
        context: &GenerationContext,
    ) {
        println!("{}", "🎉 扩展项目生成成功！".bold().green());
        println!();

        println!("{}", "📁 生成的文件结构:".bold());
        println!("  {}/", context.output_dir.display().to_string().cyan());
        println!("  ├── {}", "Cargo.toml".blue());
        println!("  ├── {}", "README.md".blue());
        println!("  └── {}/", "src".cyan());

        if context.has_layer(&LayerType::Nodes) {
            println!("      ├── {}/", "nodes".cyan());
            println!("      │   ├── {}", "mod.rs".blue());
            println!("      │   ├── {}", "node_definitions.rs".blue());
            println!("      │   └── {}", "fields.rs".blue());
        }

        if context.has_layer(&LayerType::Plugins) {
            println!("      ├── {}", "plugins/".cyan());
            println!("      │   └── {}", "mod.rs".blue());
        }

        if context.has_layer(&LayerType::Commands) {
            println!("      ├── {}/", "command".cyan());
            println!("      │   └── {}", "mod.rs".blue());
        }

        if context.has_layer(&LayerType::Router) {
            println!("      ├── {}/", "router".cyan());
            println!("      │   ├── {}", "mod.rs".blue());
            println!("      │   ├── {}", "handlers.rs".blue());
            println!("      │   └── {}", "dto.rs".blue());
        }

        println!("      └── {}", "lib.rs".blue());

        println!();
        println!("{}", "🚀 下一步操作:".bold());
        println!("  1. {} {}", "进入项目目录:".cyan(), format!("cd {}", context.output_dir.display()).yellow());
        println!("  2. {} {}", "编译项目:".cyan(), "cargo build".yellow());
        println!("  3. {} {}", "运行测试:".cyan(), "cargo test".yellow());
        println!("  4. {} {}", "添加到工作空间:".cyan(), "将项目路径添加到根 Cargo.toml 的 members 中".yellow());

        if context.has_layer(&LayerType::Router) {
            println!("  5. {} {}", "集成API路由:".cyan(), "将路由添加到Web应用中".yellow());
        }

        println!();
        println!("{} {} {}", "💡".bold(), "提示:".bold().cyan(), "生成的代码包含TODO标记，请根据实际需求完善业务逻辑。".italic());
    }
}

/// 列出可用模板的命令
pub struct ListCommand {
    detailed: bool,
}

impl ListCommand {
    pub fn new(detailed: bool) -> Self {
        Self { detailed }
    }

    pub async fn execute(&self) -> Result<()> {
        println!("{}", "📋 可用的扩展模板".bold().cyan());
        println!();

        let templates = vec![
            (ExtensionType::Standard, "包含完整四层架构的标准扩展"),
            (ExtensionType::Api, "专注于API服务的扩展"),
            (ExtensionType::Core, "核心业务逻辑扩展（无Web接口）"),
            (ExtensionType::Lightweight, "轻量级扩展（仅数据和业务逻辑层）"),
            (ExtensionType::Custom, "自定义扩展（可选择特定层组合）"),
        ];

        for (template_type, description) in templates {
            println!("{} {}", format!("{:?}", template_type).bold().green(), format!("- {}", description).italic());

            if self.detailed {
                println!("  {}", "包含的层:".cyan());
                for layer in template_type.default_layers() {
                    println!("    {} {} - {}", "•".blue(), format!("{:?}", layer).bold(), layer.description());
                }

                println!("  {}", "适用场景:".cyan());
                match template_type {
                    ExtensionType::Standard => {
                        println!("    {} Web应用、API服务、桌面应用", "•".blue());
                        println!("    {} 需要完整功能的扩展项目", "•".blue());
                    },
                    ExtensionType::Api => {
                        println!("    {} 微服务、REST API", "•".blue());
                        println!("    {} 专注于HTTP接口的项目", "•".blue());
                    },
                    ExtensionType::Core => {
                        println!("    {} 库项目、核心算法", "•".blue());
                        println!("    {} 不需要Web接口的业务逻辑", "•".blue());
                    },
                    ExtensionType::Lightweight => {
                        println!("    {} 简单的数据处理", "•".blue());
                        println!("    {} 原型开发和测试", "•".blue());
                    },
                    ExtensionType::Custom => {
                        println!("    {} 特殊需求的项目", "•".blue());
                        println!("    {} 需要特定层组合的场景", "•".blue());
                    },
                }
                println!();
            }
        }

        if !self.detailed {
            println!("{}", "💡 使用 --detailed 参数查看详细信息".italic().yellow());
        }

        Ok(())
    }
}

/// 验证项目结构的命令
pub struct ValidateCommand {
    path: PathBuf,
    fix: bool,
}

impl ValidateCommand {
    pub fn new(
        path: PathBuf,
        fix: bool,
    ) -> Self {
        Self { path, fix }
    }

    pub async fn execute(&self) -> Result<()> {
        println!("{}", format!("🔍 验证项目结构: {}", self.path.display()).bold().cyan());
        println!();

        if !self.path.exists() {
            anyhow::bail!("指定的路径不存在: {}", self.path.display());
        }

        if !self.path.is_dir() {
            anyhow::bail!("指定的路径不是目录: {}", self.path.display());
        }

        // TODO: 实现项目结构验证逻辑
        // 1. 检查 Cargo.toml 是否存在
        // 2. 检查 src/lib.rs 是否存在
        // 3. 验证各层目录结构
        // 4. 检查文件内容格式

        let cargo_toml = self.path.join("Cargo.toml");
        let src_lib = self.path.join("src/lib.rs");

        let mut issues = Vec::new();

        if !cargo_toml.exists() {
            issues.push("缺少 Cargo.toml 文件".to_string());
        }

        if !src_lib.exists() {
            issues.push("缺少 src/lib.rs 文件".to_string());
        }

        if issues.is_empty() {
            println!("{}", "✅ 项目结构验证通过".bold().green());
        } else {
            println!("{}", "❌ 发现以下问题:".bold().red());
            for issue in &issues {
                println!("  {} {}", "•".red(), issue);
            }

            if self.fix {
                println!();
                println!("{}", "🔧 自动修复功能尚未实现".yellow());
                println!("{}", "请手动修复上述问题".italic());
            }
        }

        Ok(())
    }
}

/// 配置管理命令
pub struct ConfigCommand {
    action: ConfigAction,
}

impl ConfigCommand {
    pub fn new(action: ConfigAction) -> Self {
        Self { action }
    }

    pub async fn execute(&self) -> Result<()> {
        match &self.action {
            ConfigAction::Show => {
                let config = Config::load().unwrap_or_default();
                println!("{}", "📋 当前配置".bold().cyan());
                println!("{:#}", config);
            },
            ConfigAction::Set { key, value } => {
                let mut config = Config::load().unwrap_or_default();
                config.set(key, value.clone())?;
                config.save()?;
                println!("{}", format!("✅ 设置 {} = {}", key.cyan(), value.green()).bold());
            },
            ConfigAction::Get { key } => {
                let config = Config::load().unwrap_or_default();
                if let Some(value) = config.get(key) {
                    println!("{}", value);
                } else {
                    anyhow::bail!("配置项 {} 不存在", key);
                }
            },
            ConfigAction::Reset => {
                if Confirm::new("确定要重置所有配置到默认值吗？").with_default(false).prompt()? {
                    let config = Config::default();
                    config.save()?;
                    println!("{}", "✅ 配置已重置到默认值".bold().green());
                }
            },
            ConfigAction::Init => {
                println!("{}", "⚙️  配置初始化向导".bold().cyan());
                println!();

                let mut config = Config::default();

                let author = Text::new("默认作者:").with_default("Price-RS Team").prompt()?;
                config.default_author = Some(author);

                let template_dir = Text::new("模板目录:").with_help_message("留空使用内置模板").prompt()?;

                if !template_dir.trim().is_empty() {
                    config.template_dir = Some(PathBuf::from(template_dir));
                }

                config.save()?;
                println!("{}", "✅ 配置初始化完成".bold().green());
            },
        }

        Ok(())
    }
}
